package luanvan.app.foodnote;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;


import luanvan.app.foodnote.library.AlertDialogManager;
import luanvan.app.foodnote.library.ConnectionDetector;
import luanvan.app.foodnote.library.Food;
import luanvan.app.foodnote.library.GooglePlaces;
import luanvan.app.foodnote.library.Holder;
import luanvan.app.foodnote.library.JSONParser;
import luanvan.app.foodnote.library.ParcelableFood;
import luanvan.app.foodnote.library.PlacesList;
import luanvan.app.foodnote.library.Sectionizer;
import luanvan.app.foodnote.library.SessionManager;
import luanvan.app.foodnote.library.SettingManager;
import luanvan.app.foodnote.library.SimpleSectionAdapter;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AllFoodsActivity extends SherlockActivity implements LocationListener {
	
	SessionManager session;
	private String uid;
	
	SettingManager settingManager;
	
	//how many to load on reaching the bottom
	int itemsPerPage = 15;
	boolean loadingMore = false;
	
	AlertDialogManager alertDialogManager = new AlertDialogManager();
	
	private ListView listFood;
	// ArrayList thats going to hold the search results
	List<Food> searchResults;
	// ArrayList that will hold the original Data
	List<Food> originalValues;

	// Connection detector class
    ConnectionDetector cd;
	
	
	FoodAdapter foodAdapter;
	SimpleSectionAdapter<Food> sectionAdapter;
	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();
	
	private static final int TEN_METERS = 10; // 10 meters
    private static final int TWO_MINUTES = 1000 * 60 * 2; // 2 minutes

	//ArrayList<HashMap<String, String>> foodsList;
	// url to get all products list
	private static final String url_foods_user = "http://demoluanvan.iblogger.org/get_foods_user.php"; 
	private static final String url_all_foods = "http://demoluanvan.iblogger.org/get_all_foods.php";
	private static final String url_delete_food = "http://demoluanvan.iblogger.org/delete_food.php";

	/*private static final String url_foods_user = "http://172.16.65.120/foodnoteserver/get_foods_user.php";
	private static final String url_all_foods = "http://172.16.65.120/foodnoteserver/get_all_foods.php";
	private static final String url_delete_food = "http://172.16.65.120/foodnoteserver/delete_food.php";*/

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_FOODS = "foods";
	private static final String TAG_ID = "id";
	private static final String TAG_PLACE_NAME = "TEN_DIA_DIEM";
	private static final String TAG_NAME = "TEN_MON_AN";
	private static final String TAG_ADDRESS = "DIA_CHI";
	private static final String TAG_CITY = "THANH_PHO";
	private static final String TAG_LAT = "LATITUDE";
	private static final String TAG_LNG = "LONGITUDE";
	private static final String TAG_QUAN_HUYEN = "QUAN_HUYEN";
	private static final String TAG_TYPE_FOOD_ID = "LOAI_MON_AN_id";
	private static final String TAG_UID = "unique_id";

	// products JSONArray
	JSONArray foods = null;

	private String fid, lat, lng, city;

	AlertDialogManager alert = new AlertDialogManager();

	// Google Places
	GooglePlaces googlePlaces;

	// Places List
	PlacesList nearPlaces;

	boolean flagPref = false;

	//SimpleAdapter adapter;

	// Edit search
	EditText inputSearch;
	//LayoutInflater inflater;
    
    // Search options
    int searchOptions = 1;
	
	private TextWatcher textWatcher = new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence cs, int start, int before,
				int count) {
			String searchString = inputSearch.getText().toString();
			int textLength = searchString.length();
			searchResults.clear();
			for(int i = 0; i < originalValues.size(); i++){
				
				if(searchOptions ==  1){
					String foodName = originalValues.get(i).getFood_name().toString();
					if(textLength <= foodName.length()){
						//compare the String in EditText with Names in the ArrayList
						if(searchString.equalsIgnoreCase(foodName.substring(0, textLength))){
							searchResults.add(originalValues.get(i));
							Collections.sort(searchResults);
						}
					}
				} else if(searchOptions == 2){
					String foodDist = originalValues.get(i).getDistrict().toString();
					if(textLength <= foodDist.length()){
						//compare the String in EditText with Names in the ArrayList
						if(searchString.equalsIgnoreCase(foodDist.substring(0, textLength))){
							searchResults.add(originalValues.get(i));
							Collections.sort(searchResults);
						}
					}
				} else if(searchOptions == 3){
					String foodCity = originalValues.get(i).getCity().toString();
					if(textLength <= foodCity.length()){
						//compare the String in EditText with Names in the ArrayList
						if(searchString.equalsIgnoreCase(foodCity.substring(0, textLength))){
							searchResults.add(originalValues.get(i));
							Collections.sort(searchResults);
						}
					}
				}
			}
			//adapter.getFilter().filter(cs.toString());
			foodAdapter.notifyDataSetChanged();
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			
		}
	};
	
	private LocationManager locationManager;
	private Location location;
	private String provider;
	private double getLat, getLng;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.form_places);
        
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setDisplayShowHomeEnabled(true);
		getSupportActionBar().setDisplayShowTitleEnabled(true);
		getSupportActionBar().setIcon(getResources().getDrawable(R.drawable.food_list));
		
		getSupportActionBar().show();
		
		session = new SessionManager(getApplicationContext());
		HashMap<String, String> user = session.getUserDetails();
		uid = user.get(SessionManager.KEY_UID);
		
		settingManager = new SettingManager(getApplicationContext());
		HashMap<String, String> settings = settingManager.getSetting();
		String setting = settings.get(SettingManager.KEY_SETTING);
		
		// init variable
		listFood = (ListView) findViewById(R.id.listFood);

		inputSearch = (EditText) findViewById(R.id.inputSearch);
		
		originalValues = new ArrayList<Food>();
		Food.action = 1;
		
		//new LoadFoodUser().execute();
	    //this.checkGPS(); 
		// Check internet
		//Log.d("Setting Value", String.valueOf(setting));
		if(this.checkInternet()){
			if(setting.equals("Personal"))
				new LoadFoodUser().execute();
			if(setting.equals("Public"))
				new LoadAllFoods().execute();
		}
		else 
			this.showAlertDialog(AllFoodsActivity.this, "Internet", "Bạn có muốn mở kết nối intertnet?", 1);
		
	
		// register Context Menu
		regisContextMenu();
	
		// Search food
		inputSearch.addTextChangedListener(textWatcher);
		
		this.initLocation();
		
	}

	private void initLocation(){
		// Get the location manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        provider = locationManager.getBestProvider(criteria, false);
        location = locationManager.getLastKnownLocation(provider);
		if (location != null) {
			System.out.println("Best Available provider " + provider + " has been selected.");
			this.onLocationChanged(location);
			//locationManager.requestLocationUpdates(provider, TEN_METERS, TWO_MINUTES, this);
			//Log.d("Location", String.valueOf(getLat) + ", " + String.valueOf(getLng));
		}
		else {
			Log.d("Location", "No location");
		}
	}
	
	private boolean checkGPS(){
        
   	 	locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,1.0f, (LocationListener) this);
        boolean isGPS = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER);
        return isGPS;
	}
	
	private int pos;
	private View rowView;
	private void regisContextMenu(){
		
		registerForContextMenu(listFood);
		
		listFood.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				pos = position;
				rowView = view;
				fid = ((TextView) view.findViewById(R.id.fid)).getText()
						.toString();
				lat = ((TextView) view.findViewById(R.id.lat)).getText()
						.toString();
				lng = ((TextView) view.findViewById(R.id.lng)).getText()
						.toString();
				city = ((TextView) view.findViewById(R.id.city)).getText().toString();
				// showDialog(CONTEXT_MENU_ID);
				openContextMenu(view);
			}
		});	
		
	}
	
	
	// Response from Edit Product Activity
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		/*if(checkInternet());
		if(checkGPS());*/
			//this.onLocationChanged(location);
			//locationManager.requestLocationUpdates(provider, TEN_METERS, TWO_MINUTES, this);
			//new LoadFoodUser().execute();
		// if result code 100
		if (resultCode == 100) {
			
			if(EditFoodActivity.update){
				Food f = EditFoodActivity.foodExtra.get(0).getFood();
				for(int i = 0; i < originalValues.size(); i++){
					if(f.getId().equals(foodAdapter.getItem(i).getId())){
						if(!EditFoodActivity.changeAddress){
							foodAdapter.getItem(i).setFood_name(f.getFood_name());
							foodAdapter.getItem(i).setPlace_name(f.getPlace_name());
							foodAdapter.getItem(i).setType_food_id(f.getType_food_id());
						}
						if(EditFoodActivity.changeAddress){
							foodAdapter.getItem(i).setFood_name(f.getFood_name());
							foodAdapter.getItem(i).setPlace_name(f.getPlace_name());
							foodAdapter.getItem(i).setType_food_id(f.getType_food_id());
							foodAdapter.getItem(i).setAddress(f.getAddress());
							foodAdapter.getItem(i).setCity(f.getCity());
							foodAdapter.getItem(i).setDistrict(f.getDistrict());
							foodAdapter.getItem(i).setLatitude(f.getLatitude());
							foodAdapter.getItem(i).setLongitude(f.getLongitude());
						}
						
						
						break;
					}

					
				}
				Collections.sort(foodAdapter.foods, new Comparator<Food>() {

					@Override
					public int compare(Food lhs, Food rhs) {
						// TODO Auto-generated method stub
						String name1 = lhs.getFood_name().toLowerCase();
						String name2 = rhs.getFood_name().toLowerCase();
						return name1.compareTo(name2);
					}

				});
				Collections.sort(foodAdapter.foods);

				foodAdapter.notifyDataSetChanged();
				Toast.makeText(getApplicationContext(), "Đã thêm câp nhật xong", Toast.LENGTH_LONG).show();
			}
		}
		if(resultCode == 200){
			Food addFood = NewFoodActivity.food.get(0);
			foodAdapter.add(addFood);
			Collections.sort(foodAdapter.foods, new Comparator<Food>() {

				@Override
				public int compare(Food lhs, Food rhs) {
					// TODO Auto-generated method stub
					String name1 = lhs.getFood_name().toLowerCase();
					String name2 = rhs.getFood_name().toLowerCase();
					return name1.compareTo(name2);
				}
			});
			Collections.sort(foodAdapter.foods);
			foodAdapter.notifyDataSetChanged();
			Toast.makeText(getApplicationContext(), "Đã thêm " + addFood.getFood_name(), Toast.LENGTH_LONG).show();
			
		}
		if (resultCode == 101) { 
			Log.d("Check Value", String.valueOf(SettingManager.KEY_CHECK));
			if(SettingManager.KEY_CHECK){
				HashMap<String, String> settings = settingManager.getSetting();
				String setting = settings.get(SettingManager.KEY_SETTING);
				if (setting.equals("Personal")) {
					if(searchResults != null)
						searchResults.clear();
					if(originalValues != null)
						originalValues.clear();
					//searchResults.clear();
					new LoadFoodUser().execute();
				} else if (setting.equals("Public")) {
					if(searchResults != null)
						searchResults.clear();
					if(originalValues != null)
						originalValues.clear();
					//searchResults.clear();
					new LoadAllFoods().execute();
				}
			}
		}

	}

	private class LoadFoodUser extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(AllFoodsActivity.this);
			// pDialog.setIcon(R.drawable.help);
			pDialog.setTitle("Xin chờ");
			pDialog.setMessage("Đang tải danh sách ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		
		@Override
		protected String doInBackground(String... args) {

			HashMap<String, String> user = session.getUserDetails();
			String uid = user.get(SessionManager.KEY_UID);

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("uid", uid));
			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(url_foods_user, "POST",
					params);
			// Check your log cat for JSON reponse
			Log.d("All Foods: ", json.toString());

			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					foods = json.getJSONArray(TAG_FOODS);
					for (int i = 0; i < foods.length(); i++) {
						JSONObject c = foods.getJSONObject(i);

						// Storing each json item in variable
						String id = c.getString(TAG_ID);
						String placename = c.getString(TAG_PLACE_NAME);
						String name = c.getString(TAG_NAME);
						String city = c.getString(TAG_CITY);
						String address = c.getString(TAG_ADDRESS);
						String lat = c.getString(TAG_LAT);
						String lng = c.getString(TAG_LNG);
						String type_food_id = c.getString(TAG_TYPE_FOOD_ID);
						String quan_huyen = c.getString(TAG_QUAN_HUYEN);
						
						//Districts.add(quan_huyen);
						
						originalValues.add(new Food(id, type_food_id, placename, name, address, quan_huyen, city, 
								Double.parseDouble(lat), Double.parseDouble(lng)));
						
						
					}
					searchResults = new ArrayList<Food>(originalValues);
				} else {
					// no products found
					// Launch Add New product Activity
					/*
					 * Intent i = new Intent(getApplicationContext(),
					 * NewProductActivity.class); // Closing all previous
					 * activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					 * startActivity(i);
					 */
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			pDialog.dismiss();
			
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					
					if(searchResults != null)
						Collections.sort(searchResults);
					foodAdapter = new FoodAdapter(AllFoodsActivity.this, R.layout.row, searchResults);
					// Wrap your existing adapter with the SimpleSectionAdapter
					
					sectionAdapter = new SimpleSectionAdapter<Food>(getApplicationContext(), foodAdapter,
							R.layout.section_header, R.id.title, new FoodSectionizer());
					//add the footer before adding the adapter, else the footer will nod load!
					
					/*View footerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).
							inflate(R.layout.loading_view, null, false);
					listFood.addFooterView(footerView);*/
					listFood.setAdapter(sectionAdapter);


				}
			});
		}

	}

	private class LoadAllFoods extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(AllFoodsActivity.this);
			pDialog.setTitle("Xin chờ");
			pDialog.setMessage("Đang tải danh sách ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... agrs) {

			List<NameValuePair> params = new ArrayList<NameValuePair>();
			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(url_all_foods, "GET",
					params);
			// Check your log cat for JSON reponse
			Log.d("All Foods: ", json.toString());

			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					foods = json.getJSONArray(TAG_FOODS);
					for (int i = 0; i < foods.length(); i++) {
						JSONObject c = foods.getJSONObject(i);

						// Storing each json item in variable
						String id = c.getString(TAG_ID);
						String placename = c.getString(TAG_PLACE_NAME);
						String name = c.getString(TAG_NAME);
						String city = c.getString(TAG_CITY);
						String address = c.getString(TAG_ADDRESS);
						String lat = c.getString(TAG_LAT);
						String lng = c.getString(TAG_LNG);
						String type_food_id = c.getString(TAG_TYPE_FOOD_ID);
						String quan_huyen = c.getString(TAG_QUAN_HUYEN);

						originalValues.add(new Food(id, type_food_id, placename, name, address, quan_huyen, city, 
								Double.parseDouble(lat), Double.parseDouble(lng)));
						
					}
					searchResults = new ArrayList<Food>(originalValues);
				} else {
					// no products found
					// Launch Add New product Activity
					
					/* Intent i = new Intent(getApplicationContext(), NewProductActivity.class); // Closing all previous
					 activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					 startActivity(i);*/
					 
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		protected void onPostExecute(String file_url) {
			pDialog.dismiss();
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 */
					if(searchResults != null)
						Collections.sort(searchResults);
					foodAdapter = new FoodAdapter(AllFoodsActivity.this, R.layout.row, searchResults);
					// Wrap your existing adapter with the SimpleSectionAdapter
					
					sectionAdapter = new SimpleSectionAdapter<Food>(getApplicationContext(), foodAdapter,
							R.layout.section_header, R.id.title, new FoodSectionizer());
					listFood.setAdapter(sectionAdapter);
					listFood.setFastScrollEnabled(true);
				}
			});
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(provider, TEN_METERS, TWO_MINUTES, this);
	}

	@Override
	protected void onPause() {
		super.onPause();
	    locationManager.removeUpdates(this);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Tùy chọn");
		menu.setHeaderIcon(R.drawable.submenu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		Long id = listFood.getItemIdAtPosition(info.position);
		//Long id = getListAdpter.getItemId(info.position);
		Log.d("id = ", String.valueOf(id));
		switch (item.getItemId()) {
		case R.id.update:
			Intent intentFoodPlace = new Intent(AllFoodsActivity.this,
					EditFoodActivity.class);
			intentFoodPlace.putExtra(TAG_ID, fid);
			//Log.d("FOOD_ID", fid);
			startActivityForResult(intentFoodPlace, 100);
			return true;

		case R.id.delete:
			new DelectFood().execute();
			return true;
		case R.id.food_places:
			Intent googlePlaces = new Intent(AllFoodsActivity.this,
					GooglePlacesActivity.class);
			googlePlaces.putExtra(TAG_LAT, Double.valueOf(lat));
			googlePlaces.putExtra(TAG_LNG, Double.valueOf(lng));
			startActivity(googlePlaces);
			return true;

		case R.id.direction:
			if(checkGPS()){
				String dirMap = "http://maps.google.com/maps?";
				StringBuffer sBuf = new StringBuffer(dirMap);
				sBuf.append("saddr=");
				sBuf.append(getLat);
				sBuf.append(',');
				sBuf.append(getLng);
				sBuf.append("&daddr=");
				sBuf.append(Double.valueOf(lat));
				sBuf.append(',');
				sBuf.append(Double.valueOf(lng));
				Intent direction = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(sBuf.toString()));
				startActivity(direction);
			} else {
				this.showAlertDialog(AllFoodsActivity.this, "GPS", "Bạn có muốn bật GPS?", 2);
			}
			return true;

		case R.id.FoodInCity:
			/*Intent listTypeFood = new Intent(getApplicationContext(), FoodInCityActivity.class);
			listTypeFood.putExtra(TAG_CITY, city);
			startActivity(listTypeFood);*/
			//Food.action = 2;
			ArrayList<ParcelableFood> foodExtra = new ArrayList<ParcelableFood>();
			
			ArrayList<Food> arrayListFood = LoadFoodInCity(city);
			for(int i = 0; i < arrayListFood.size(); i++){
				foodExtra.add(new ParcelableFood(arrayListFood.get(i)));
			}
			Intent listFoodInCity = new Intent(getApplicationContext(), FoodInCityActivity.class);
			listFoodInCity.putExtra(TAG_CITY, foodExtra);
			listFoodInCity.putExtra("nameCity", city);
			startActivity(listFoodInCity);
			return true;
		}
		return (super.onOptionsItemSelected(item));
	}

	 /** Callback function */
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu, menu);
		
        return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
	    switch(item.getItemId()){
	    case R.id.addFood:
	    	Intent newFood = new Intent(AllFoodsActivity.this, NewFoodActivity.class);
	    	startActivityForResult(newFood, 200);
	        return true;
	    case R.id.showListFood:
	    	Intent i = new Intent(AllFoodsActivity.this, ShowSettingActivity.class);
	    	startActivityForResult(i, 101);
	    	return true;
	    case R.id.searchName:
	    	searchOptions = 1;
	    	return true;
	    	
	    case R.id.search_quan_huyen:
	    	searchOptions = 2;
	    	return true;
	    case R.id.searchCity:
	    	searchOptions = 3;
	    	return true;
	    	
	    case R.id.quitFood:
	    	session.logoutUser();
	    	finish();
	    	return true;
	    }
	    return false;
	}
	
	/**
	 * Setting show list view
	 * 
	 * @return
	 */
	/*private void getListPrefValues() {
		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		
		String listPrefValues = settings.getString("showlist", "1");
		if(Integer.parseInt(listPrefValues) == 1)
			settingManager.createSetting(1);
		if(Integer.parseInt(listPrefValues) == 2)
			settingManager.createSetting(2);
	}*/

	private class FoodAdapter extends ArrayAdapter<Food> {

		private List<Food> foods;
		public FoodAdapter(Context context, int textViewResourceId, List<Food> foods) {
			super(context, textViewResourceId, foods);
			// TODO Auto-generated constructor stub
			this.foods = foods;
		}

		@Override
		public int getCount(){ 
			return foods != null ? foods.size() : 0;
		}
		
		@Override
        public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			Holder holder = null;
			if(view == null){
				
				view = View.inflate(AllFoodsActivity.this, R.layout.row, null);
				
				holder = new Holder();
				// cache the views
				
				holder.setIconImageView((ImageView) view.findViewById(R.id.icon));
				holder.setIdTextView((TextView) view.findViewById(R.id.fid));
				holder.setLatitudeTextView((TextView) view.findViewById(R.id.lat));
				holder.setLongitudeTextView((TextView) view.findViewById(R.id.lng));
				holder.setCityTextView((TextView) view.findViewById(R.id.city));
				holder.setTypeFoodIdTextView((TextView) view.findViewById(R.id.type_food_id));
				holder.setFoodNameTextView((TextView) view.findViewById(R.id.foodname));
				holder.setPlaceNameTextView((TextView) view.findViewById(R.id.placename));
				holder.setAddresstTextView((TextView) view.findViewById(R.id.address));
				
				
				view.setTag(holder);
			} else {
				holder = (Holder) view.getTag();
			}
			// Set properties
			final Food food = foods.get(position);
			
			holder.getIdTextView().setText(food.getId());
			
			holder.getLatitudeTextView().setText(String.valueOf(food.getLatitude()));
			
			holder.getLongitudeTextView().setText(String.valueOf(food.getLongitude()));
			
			holder.getCityTextView().setText(food.getCity());
			
			holder.getTypeFoodIdTextView().setText(food.getType_food_id());
			
			holder.getFoodNameTextView().setText(food.getFood_name());
			
			holder.getPlaceNameTextView().setText(food.getPlace_name());
			
			holder.getAddresstTextView().setText(food.getAddress());
			
			if(Integer.valueOf(food.getType_food_id()) == 1){
				holder.getIconImageView().setImageResource(R.drawable.icon_fast_food);
			} else if(Integer.valueOf(food.getType_food_id()) == 2){
				holder.getIconImageView().setImageResource(R.drawable.dessert);
			} else if(Integer.valueOf(food.getType_food_id()) == 3){
				holder.getIconImageView().setImageResource(R.drawable.drink_icon);
			}
			holder.getIconImageView().setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					ArrayList<ParcelableFood> foodExtra = new ArrayList<ParcelableFood>();
					String type = food.getType_food_id();
					ArrayList<Food> type_of_food = LoadTypeOfFood(type);
					
					for(int i = 0; i < type_of_food.size(); i++){
						foodExtra.add(new ParcelableFood(type_of_food.get(i)));
					}
					Intent TypeOfFood = new Intent(getApplicationContext(), TypeOfFoodActivity.class);
					TypeOfFood.putExtra(TAG_TYPE_FOOD_ID, foodExtra);
					startActivity(TypeOfFood);
				}
			});
			
			
			return view;
		}
		
	}

    class FoodSectionizer implements Sectionizer<Food>{

		@Override
		public String getSectionTitleForItem(Food instance) {
			// TODO Auto-generated method stub
			return instance.getCity();
		}
    	
    }

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		getLat = location.getLatitude();
		getLng = location.getLongitude();
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
    
    public ArrayList<Food> LoadFoodInCity(String city){
    	ArrayList<Food> temp = new ArrayList<Food>();
    	if(temp != null) temp.clear();
    	for(int i = 0; i < originalValues.size(); i++){
			if(originalValues.get(i).getCity().equals(city)){
				temp.add(originalValues.get(i));
			}
		}
		return temp;
    }
  
    private ArrayList<Food> LoadTypeOfFood(String typeId){
    	ArrayList<Food> temp = new ArrayList<Food>();
    	if(temp != null) temp.clear();
    	for(int i = 0; i < originalValues.size(); i++){
    		if(originalValues.get(i).getType_food_id().equals(typeId))
    			temp.add(originalValues.get(i));
    	}
		return temp;
    	
    }
    class FoodInCitySectionizer implements Sectionizer<Food>{

		@Override
		public String getSectionTitleForItem(Food instance) {
			// TODO Auto-generated method stub
			return instance.getDistrict();
		}
    	
    }
    
    private boolean checkInternet(){
    	boolean isInternetPresent;
    	cd = new ConnectionDetector(getApplicationContext());
        isInternetPresent = cd.isConnectingToInternet();
        return isInternetPresent;
    }

    private void showAlertDialog(Context context, String title, String message, final int alert) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(context);
 
        // Setting Dialog Title
        dialog.setTitle(title);
 
        // Setting Dialog Message
        dialog.setMessage(message);
 
        dialog.setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if(alert == 1) // for internet
					startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS), 0);
				if(alert == 2) // for GPS
					startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
			}
		});
        dialog.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
        // Setting alert dialog icon
        if(alert == 1)
        	dialog.setIcon(R.drawable.intetnet);
        if(alert == 2)
        	dialog.setIcon(R.drawable.satellite);
 
        AlertDialog alertDialog = dialog.create();
        alertDialog.show();
    }
    
    private class DelectFood extends AsyncTask<String, String, String>{
		int success;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(AllFoodsActivity.this);
			pDialog.setMessage("Đang xóa ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		@Override
		protected String doInBackground(String... args) {
			
			//String message;
			try {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair(TAG_ID, fid));
				params.add(new BasicNameValuePair(TAG_UID, uid));
				JSONObject json = jParser.makeHttpRequest(url_delete_food, "POST", params);
				
				// check your log for json response
                Log.d("Delete Food", json.toString());
                success = json.getInt(TAG_SUCCESS);
                if(success == 1){
                	runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							final int position = pos - 1;
							removeListItem(rowView, position);
						}
					});
                	
                }
			} catch (JSONException e) {
                e.printStackTrace();
            }
			return null;
		}
		protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if(success == 0){
            	alertDialogManager.showAlertDialog(AllFoodsActivity.this, "Xóa món ăn", "Không tìm thấy", false);
            } else if(success == 2){
            	alertDialogManager.showAlertDialog(AllFoodsActivity.this, "Xóa món ăn", "Bạn không có quyền xóa món ăn này", false);
            } else if(success == 3){
            	alertDialogManager.showAlertDialog(AllFoodsActivity.this, "Xóa món ăn", "Dữ liệu yêu cầu bị thiếu", false);
            }
            
        }
		 
	 }
    
    protected void removeListItem(View rowView, final int positon) {
    	final Animation animation = AnimationUtils.loadAnimation(rowView.getContext(), R.anim.splashfadeout);
    	rowView.startAnimation(animation);
    	Handler handle = new Handler();
    	handle.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				//foodAdapter.foods.get(pos);
				Food f = foodAdapter.foods.get(positon);
				Log.i("Position", String.valueOf(positon));
				foodAdapter.remove(f);
				foodAdapter.notifyDataSetChanged();
				sectionAdapter.notifyDataSetChanged();
				animation.cancel();
				Toast.makeText(getApplicationContext(), "Đã xóa " + f.getFood_name(), Toast.LENGTH_LONG).show();
			}
		}, 1000);
    }
}
